package be.rhok.eenzaamheidswijzer.filter.util;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class ByteArrayServletOutputStream extends ServletOutputStream {

    private byte buf[];
    private int count;

    public ByteArrayServletOutputStream() {
        this(32);
    }

    public ByteArrayServletOutputStream(int size) {
        if (size < 0) {
            throw new IllegalArgumentException("Negative initial size: " + size);
        }
        buf = new byte[size];
    }

    public synchronized byte toByteArray()[] {
        return Arrays.copyOf(buf, count);
    }

    public synchronized void reset() {
        count = 0;
    }

    public synchronized int size() {
        return count;
    }

    public void enlarge(int size) {
        if (size > buf.length) {
            buf = Arrays.copyOf(buf, Math.max(buf.length << 1, size));
        }
    }

    @Override
    public synchronized void write(int b) throws IOException {
        int newcount = count + 1;
        enlarge(newcount);
        buf[count] = (byte) b;
        count = newcount;
    }
}